<template>
  <div class="project-group-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>项目组管理</h2>
    </div>

    <!-- 搜索和操作区域 -->
    <div class="toolbar">
      <div class="search-area">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入项目组名称或描述"
          clearable
          class="search-input"
          @keyup.enter="handleSearch"
        >
          <template #prefix>
            <el-icon>
              <Search />
            </el-icon>
          </template>
        </el-input>
        <el-button type="primary" @click="handleSearch">
          <el-icon>
            <Search />
          </el-icon>
          搜索
        </el-button>
        <el-button @click="handleReset">重置</el-button>
      </div>

      <div class="action-area">
        <el-button type="primary" @click="handleAdd">
          <el-icon>
            <Plus />
          </el-icon>
          添加
        </el-button>
        <el-button type="warning" :disabled="selectedRows.length !== 1" @click="handleSelectEdit">
          <el-icon>
            <Edit />
          </el-icon>
          修改
        </el-button>
        <el-button type="danger" :disabled="selectedRows.length === 0" @click="handleBatchDelete">
          <el-icon>
            <Delete />
          </el-icon>
          批量删除
        </el-button>
      </div>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <el-table
        :data="tableData"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="loading"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="groupName" label="项目组名称" min-width="150" />
        <el-table-column prop="groupCode" label="项目组编码" min-width="200" />
        <el-table-column prop="belongToGroup" label="所属上级组织" width="120" />
        <el-table-column prop="belongToCustomer" label="所属客户" width="100" />
        <el-table-column prop="generalDepartment" label="归属部门" width="100" />
        <el-table-column prop="department" label="具体部门" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">
              {{ scope.row.status === 1 ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="scope">
            <div class="action-buttons">
              <el-button class="mini-btn" @click="handleView(scope.row)">
                <el-icon>
                  <View />
                </el-icon>
                查看
              </el-button>
              <el-button class="mini-btn" type="primary" @click="handleEdit(scope.row)">
                <el-icon>
                  <Edit />
                </el-icon>
                编辑
              </el-button>
              <el-button class="mini-btn" type="danger" @click="handleDelete(scope.row)">
                <el-icon>
                  <Delete />
                </el-icon>
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog v-model="openAddOrUpdate" :title="openAddOrUpdateTitle" width="500">
      <el-form :model="addOrUpdateData" label-width="auto">
        <el-form-item label="项目组名称">
          <el-input v-model="addOrUpdateData.groupName" autocomplete="off" />
        </el-form-item>
        <el-form-item label="项目组编码">
          <el-input v-model="addOrUpdateData.groupCode" autocomplete="off" />
        </el-form-item>
        <el-form-item label="所属上级组织">
          <el-input v-model="addOrUpdateData.belongToGroup" autocomplete="off" />
        </el-form-item>
        <el-form-item label="所属客户">
          <el-input v-model="addOrUpdateData.belongToCustomer" autocomplete="off" />
        </el-form-item>
        <el-form-item label="归属部门">
          <el-input v-model="addOrUpdateData.generalDepartment" autocomplete="off" />
        </el-form-item>
        <el-form-item label="具体部门">
          <el-input v-model="addOrUpdateData.department" autocomplete="off" />
        </el-form-item>
        <el-form-item label="是否启用">
          <el-switch
            v-model="addOrUpdateData.active"
            class="ml-2"
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancelAddOrUpdate">取消</el-button>
          <el-button type="primary" @click="saveAddOrUpdate">保存</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="openDetail" title="项目组详情" width="600px">
      <div class="detail-container" v-loading="detailLoading">
        <!-- 基本信息卡片 -->
        <el-card class="detail-card" shadow="never">
          <template #header>
            <div class="card-header">
              <el-icon><Document /></el-icon>
              <span>基本信息</span>
            </div>
          </template>

          <el-row :gutter="20">
            <el-col :span="12">
              <div class="detail-item">
                <el-text class="detail-label" type="info">项目组名称：</el-text>
                <el-text class="detail-value">{{ detailData.groupName || '-' }}</el-text>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <el-text class="detail-label" type="info">项目组编码：</el-text>
                <el-text class="detail-value">{{ detailData.groupCode || '-' }}</el-text>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <el-text class="detail-label" type="info">所属上级组织：</el-text>
                <el-text class="detail-value">{{ detailData.belongToGroup || '-' }}</el-text>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <el-text class="detail-label" type="info">所属客户：</el-text>
                <el-text class="detail-value">{{ detailData.belongToCustomer || '-' }}</el-text>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <el-text class="detail-label" type="info">归属部门：</el-text>
                <el-text class="detail-value">{{ detailData.generalDepartment || '-' }}</el-text>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <el-text class="detail-label" type="info">具体部门：</el-text>
                <el-text class="detail-value">{{ detailData.department || '-' }}</el-text>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <el-text class="detail-label" type="info">项目类别：</el-text>
                <el-text class="detail-value">{{ detailData.category || '-' }}</el-text>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="detail-item">
                <el-text class="detail-label" type="info">状态：</el-text>
                <el-tag :type="detailData.status === 1 ? 'success' : 'info'" size="small">
                  {{ detailData.status === 1 ? '启用' : '停用' }}
                </el-tag>
              </div>
            </el-col>
          </el-row>
        </el-card>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="openDetail = false">
            <el-icon><Close /></el-icon>
            关闭
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import api from '@/api'
import { Delete, Edit, Plus, Search, View } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { onMounted, ref } from 'vue'

// 响应式数据
const searchKeyword = ref('')
const selectedRows = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])
const addOrUpdateData = ref({})
const openAddOrUpdate = ref(false)
const openAddOrUpdateTitle = ref('添加项目组')
const openDetail = ref(false)
const detailData = ref({})
const detailLoading = ref(false)

const getPageListApi = async () => {
  const params = {
    page: currentPage.value,
    size: pageSize.value,
    filter: searchKeyword.value
  }
  const { data: res } = await api.projectGroupList(params)
  if (res?.code === 200) {
    tableData.value =
      res.data.records?.map(item => ({
        id: item.id,
        groupName: item.groupName,
        groupCode: item.groupCode,
        belongToGroup: item.belongToGroup,
        belongToCustomer: item.belongToCustomer,
        generalDepartment: item.generalDepartment,
        department: item.department,
        status: item.status
      })) || []
    total.value = res.data.totalRow
    return
  }
  ElMessage.error(res?.message || '获取项目组列表失败')
}

const addOrUpdateApi = async () => {
  // check if data is valid
  const { data: res } = await api.projectGroupSave({
    ...addOrUpdateData.value,
    status: addOrUpdateData.value.active ? 1 : 0
  })
  if (res?.code === 200) {
    ElMessage.success('保存成功')
    await getPageListApi()
  } else {
    ElMessage.error(res?.message || '保存失败')
  }
}

const deleteApi = async id => {
  const { data: res } = await api.projectGroupDelete(id)
  if (res?.code === 200) {
    ElMessage.success('删除成功')
    await getPageListApi()
  } else {
    ElMessage.error(res?.message || '删除失败')
  }
}

const cancelAddOrUpdate = () => {
  openAddOrUpdate.value = false
  addOrUpdateData.value = {}
}

const saveAddOrUpdate = async () => {
  // save or update logic here
  await addOrUpdateApi()
  openAddOrUpdate.value = false
}

// 方法
const handleSearch = async () => {
  loading.value = true
  // 模拟搜索请求
  await getPageListApi()
  loading.value = false
}

const handleReset = async () => {
  searchKeyword.value = ''
  selectedRows.value = []
  await handleSearch()
}

const handleAdd = () => {
  openAddOrUpdateTitle.value = '添加项目组'
  openAddOrUpdate.value = true
  addOrUpdateData.value = {
    active: true
  }
}

const handleEdit = row => {
  openAddOrUpdateTitle.value = '编辑项目组'
  openAddOrUpdate.value = true
  // 表格中的信息最好调用后台接口获取
  addOrUpdateData.value = {
    ...row,
    // 将数字状态转换为布尔值用于 el-switch
    active: row.status === 1
  }
}

const handleDelete = row => {
  ElMessageBox.confirm(`确定要删除项目组 "${row.groupName}" 吗？`, '确认删除', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      // 这里应该调用删除API
      await deleteApi({ id: row.id })
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

const handleView = async row => {
  const id = row.id
  detailData.value = {}
  detailLoading.value = true
  openDetail.value = true
  const { data: res } = await api.projectGroupInfo(id)
  detailLoading.value = false
  if (res?.code !== 200) {
    ElMessage.error(res?.message || '获取项目组详情失败')
    openDetail.value = false
    return
  }

  detailData.value = {
    ...res.data
  }
}

const handleSelectEdit = () => {
  if (selectedRows.value.length !== 1) {
    ElMessage.warning('请先选择一个项目组进行编辑')
    return
  }
  const row = selectedRows.value[0]
  handleEdit(row)
}

const handleBatchDelete = () => {
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRows.value.length} 个项目组吗？`,
    '确认批量删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      const ids = selectedRows.value.map(item => item.id)
      // TODO check if ids is empty
      if (ids.length === 0) {
        ElMessage.warning('没有选中任何项目组')
        return
      }
      const { data: res } = await api.projectGroupList({ ids: ids })
      if (res?.code === 200) {
        ElMessage.success('批量删除成功')
        selectedRows.value = []
        await getPageListApi()
      } else {
        ElMessage.error(res?.message || '批量删除失败')
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
}

const handleSelectionChange = selection => {
  selectedRows.value = selection
}

const handleSizeChange = async val => {
  pageSize.value = val
  await handleSearch()
}

const handleCurrentChange = async val => {
  currentPage.value = val
  await handleSearch()
}

// 生命周期
onMounted(() => {
  getPageListApi()
})
</script>

<style lang="scss" scoped>
.project-group-container {
  padding: 0;

  .page-header {
    margin-bottom: 20px;

    h2 {
      margin: 0;
      color: #303133;
      font-weight: 600;
    }
  }

  .toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 16px;
    background: #f8f9fa;
    border-radius: 8px;

    .search-area {
      display: flex;
      align-items: center;
      gap: 12px;

      .search-input {
        width: 300px;
      }
    }

    .action-area {
      display: flex;
      gap: 12px;
    }
  }

  .table-container {
    background: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  .pagination-container {
    display: flex;
    justify-content: center;
    margin-top: 20px;
  }
}

// 响应式设计
@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    gap: 16px;

    .search-area {
      width: 100%;

      .search-input {
        flex: 1;
        width: auto;
      }
    }

    .action-area {
      width: 100%;
      justify-content: center;
    }
  }
}

.action-buttons {
  display: flex;
  gap: 4px;

  .mini-btn {
    height: 24px;
    padding: 0 8px;
    font-size: 12px;
    min-width: auto;

    .el-icon {
      font-size: 12px;
      margin-right: 2px;
    }
  }
}
</style>
